package dom.example.lucene.utils;

import io.swagger.models.auth.In;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.*;
import org.apache.poi.ss.formula.functions.T;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author X.I.O
 * @title: LuceneSearchUtils
 * @projectName demo
 * @description: TODO
 * @date 2021/11/6 21:07
 */
public class LuceneSearchUtils extends LuceneUtils {

    public static Map<String, Object> selectPages(Integer page,Integer size,String indexName,
                                                        String field,String keyword) throws Exception{
        Query query = new TermQuery(new Term(field, keyword));
        Map<String, Object> objectMap=selectPages(indexName,query,page,size);
        return objectMap;
    }

    public static Map<String, Object> selectPages(String indexName,Query query,Integer page,Integer size) throws Exception{
        IndexSearcher indexSearcher=createIndexSearcher(indexName);
        Integer start=(page-1)*size;
        Integer total=start+size;
        TopDocs topDocs = indexSearcher.search(query, total);
        //返回的条数
        int count = Math.min(topDocs.totalHits, total);
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        List<Document> documents=getDocumentByScore(scoreDocs,indexSearcher);
        List<Map<String, Object>> objectMaps=getDocumentArrayToMapArray(documents);
        List<Map<String, Object>> pageMapList=pageSub(total,size,objectMaps);
        Map<String, Object> objectMap=new HashMap<>();
        objectMap.put("total",count);
        objectMap.put("data",pageMapList);
        objectMap.put("size",size);
        return objectMap;
    }



    /**
     * 自定义查询器
     * @param indexName
     * @param query
     * @param total
     * @return
     * @throws Exception
     */
    public static List<Map<String, Object>> searchQuery(String indexName,Query query,Integer total) throws Exception{
        IndexSearcher indexSearcher=createIndexSearcher(indexName);
        TopDocs topDocs = indexSearcher.search(query, total);
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        List<Document> documents=getDocumentByScore(scoreDocs,indexSearcher);
        List<Map<String, Object>> objectMaps=getDocumentArrayToMapArray(documents);
        return objectMaps;
    }

    public static <T> List<T> searchListQuery(String indexName,Query query,Class<T> cls,Integer toatl)throws Exception{
        List<Map<String, Object>> objectMaps=searchQuery(indexName,query,toatl);
        return mapsToObjects(objectMaps,cls);
    }

    private static List<Map<String, Object>> pageSub(Integer total,Integer size,List<Map<String, Object>> objects){
        List<Map<String, Object>> mapList=new ArrayList<>(size);
        for (int i = total; i < objects.size() ; i++) {
            mapList.add(objects.get(i));
        }
        objects=null;
        return mapList;
    }
}
